import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../constants/app_constants.dart';
import '../network/api_response.dart';
import 'base_controller.dart';

abstract class ListController<T> extends BaseController {
  // 数据列表
  final _items = <T>[].obs;
  List<T> get items => _items;
  
  // 分页相关
  final _currentPage = 1.obs;
  int get currentPage => _currentPage.value;
  
  final _pageSize = AppConstants.pageSize.obs;
  int get pageSize => _pageSize.value;
  
  final _totalItems = 0.obs;
  int get totalItems => _totalItems.value;
  
  final _totalPages = 0.obs;
  int get totalPages => _totalPages.value;
  
  final _hasMore = true.obs;
  bool get hasMore => _hasMore.value;
  
  // 刷新控制器
  final RefreshController refreshController = RefreshController(initialRefresh: false);
  
  // 搜索相关
  final _searchKeyword = ''.obs;
  String get searchKeyword => _searchKeyword.value;
  
  // 过滤相关
  final _filterParams = <String, dynamic>{}.obs;
  Map<String, dynamic> get filterParams => _filterParams;
  
  // 排序相关
  final _sortBy = ''.obs;
  String get sortBy => _sortBy.value;
  
  final _sortOrder = 'desc'.obs;
  String get sortOrder => _sortOrder.value;
  
  @override
  void onInit() {
    super.onInit();
    print('ListController onInit called');
  }
  
  @override
  void onReady() {
    super.onReady();
    print('ListController onReady called');
    loadData();
  }
  
  @override
  void onClose() {
    refreshController.dispose();
    super.onClose();
  }
  
  // 加载数据
  Future<void> loadData({bool showLoading = true}) async {
    try {
      print('loadData called with showLoading: $showLoading');
      if (showLoading) {
        print('Setting loading state');
        setViewState(ViewState.loading);
      }
      
      _currentPage.value = 1;
      print('Calling fetchData...');
      final result = await fetchData(
        page: currentPage,
        pageSize: pageSize,
        keyword: searchKeyword,
        filters: filterParams,
        sortBy: sortBy,
        sortOrder: sortOrder,
      );
      
      print('fetchData completed with success: ${result.isSuccess}');
      if (result.isSuccess) {
        print('Handling pagination response...');
        _handlePaginationResponse(result.data!);
      } else {
        print('fetchData failed: ${result.errorMessage}');
        showError(result.errorMessage ?? '加载数据失败');
      }
    } catch (e) {
      print('loadData error: $e');
      handleException(e);
    }
  }
  
  // 刷新数据
  @override
  Future<void> onRefresh() async {
    try {
      _currentPage.value = 1;
      final result = await fetchData(
        page: currentPage,
        pageSize: pageSize,
        keyword: searchKeyword,
        filters: filterParams,
        sortBy: sortBy,
        sortOrder: sortOrder,
      );
      
      if (result.isSuccess) {
        _handlePaginationResponse(result.data!);
        refreshController.refreshCompleted();
        setViewState(ViewState.success);
      } else {
        refreshController.refreshFailed();
        showError(result.errorMessage ?? '刷新失败');
      }
    } catch (e) {
      refreshController.refreshFailed();
      handleException(e);
    }
  }
  
  // 加载更多数据
  @override
  Future<void> onLoadMore() async {
    if (!hasMore) {
      refreshController.loadNoData();
      return;
    }
    
    try {
      _currentPage.value++;
      final result = await fetchData(
        page: currentPage,
        pageSize: pageSize,
        keyword: searchKeyword,
        filters: filterParams,
        sortBy: sortBy,
        sortOrder: sortOrder,
      );
      
      if (result.isSuccess) {
        final pagination = result.data!;
        _items.addAll(pagination.items);
        _totalItems.value = pagination.total;
        _totalPages.value = pagination.totalPages;
        _hasMore.value = pagination.hasNext;
        
        if (hasMore) {
          refreshController.loadComplete();
        } else {
          refreshController.loadNoData();
        }
      } else {
        _currentPage.value--;
        refreshController.loadFailed();
        showErrorMessage(result.errorMessage ?? '加载失败');
      }
    } catch (e) {
      _currentPage.value--;
      refreshController.loadFailed();
      handleException(e);
    }
  }
  
  // 重试操作
  @override
  Future<void> onRetry() async {
    await loadData();
  }
  
  // 搜索
  Future<void> search(String keyword) async {
    _searchKeyword.value = keyword;
    await loadData();
  }
  
  // 清除搜索
  Future<void> clearSearch() async {
    _searchKeyword.value = '';
    await loadData();
  }
  
  // 设置过滤参数
  Future<void> setFilter(Map<String, dynamic> filters) async {
    _filterParams.value = filters;
    await loadData();
  }
  
  // 添加过滤参数
  Future<void> addFilter(String key, dynamic value) async {
    _filterParams[key] = value;
    await loadData();
  }
  
  // 移除过滤参数
  Future<void> removeFilter(String key) async {
    _filterParams.remove(key);
    await loadData();
  }
  
  // 清除过滤参数
  Future<void> clearFilters() async {
    _filterParams.clear();
    await loadData();
  }
  
  // 设置排序
  Future<void> setSort(String sortBy, {String sortOrder = 'desc'}) async {
    _sortBy.value = sortBy;
    _sortOrder.value = sortOrder;
    await loadData();
  }
  
  // 切换排序顺序
  Future<void> toggleSortOrder() async {
    _sortOrder.value = sortOrder == 'desc' ? 'asc' : 'desc';
    await loadData();
  }
  
  // 清除排序
  Future<void> clearSort() async {
    _sortBy.value = '';
    _sortOrder.value = 'desc';
    await loadData();
  }
  
  // 添加项目
  void addItem(T item) {
    _items.add(item);
    _totalItems.value++;
  }
  
  // 插入项目
  void insertItem(int index, T item) {
    _items.insert(index, item);
    _totalItems.value++;
  }
  
  // 更新项目
  void updateItem(int index, T item) {
    if (index >= 0 && index < _items.length) {
      _items[index] = item;
    }
  }
  
  // 删除项目
  void removeItem(T item) {
    _items.remove(item);
    _totalItems.value--;
  }
  
  // 根据索引删除项目
  void removeItemAt(int index) {
    if (index >= 0 && index < _items.length) {
      _items.removeAt(index);
      _totalItems.value--;
    }
  }
  
  // 清空列表
  void clearItems() {
    _items.clear();
    _totalItems.value = 0;
    _totalPages.value = 0;
    _hasMore.value = true;
    _currentPage.value = 1;
  }
  
  // 查找项目
  T? findItem(bool Function(T item) predicate) {
    try {
      return _items.firstWhere(predicate);
    } catch (e) {
      return null;
    }
  }
  
  // 查找项目索引
  int findItemIndex(bool Function(T item) predicate) {
    for (int i = 0; i < _items.length; i++) {
      if (predicate(_items[i])) {
        return i;
      }
    }
    return -1;
  }
  
  // 获取项目
  T? getItem(int index) {
    if (index >= 0 && index < _items.length) {
      return _items[index];
    }
    return null;
  }
  
  // 获取项目数量
  int get itemCount => _items.length;
  
  // 是否为空
  bool get isEmpty => _items.isEmpty;
  
  // 是否不为空
  bool get isNotEmpty => _items.isNotEmpty;
  
  // 处理分页响应
  void _handlePaginationResponse(PaginationResponse<T> response) {
    print('_handlePaginationResponse called with ${response.items.length} items');
    _items.value = response.items;
    _totalItems.value = response.total;
    _totalPages.value = response.totalPages;
    _hasMore.value = response.hasNext;
    
    if (response.items.isEmpty) {
      print('No items, showing empty state');
      showEmpty();
    } else {
      print('Items found, showing success state');
      showSuccess();
    }
  }
  
  // 设置页面大小
  void setPageSize(int size) {
    _pageSize.value = size;
  }
  
  // 跳转到指定页面
  Future<void> goToPage(int page) async {
    if (page > 0 && page <= totalPages) {
      _currentPage.value = page;
      await loadData();
    }
  }
  
  // 获取分页信息
  Map<String, dynamic> get paginationInfo => {
    'currentPage': currentPage,
    'pageSize': pageSize,
    'totalItems': totalItems,
    'totalPages': totalPages,
    'hasMore': hasMore,
  };
  
  // 获取搜索和过滤信息
  Map<String, dynamic> get searchFilterInfo => {
    'keyword': searchKeyword,
    'filters': filterParams,
    'sortBy': sortBy,
    'sortOrder': sortOrder,
  };
  
  // 导出数据
  List<Map<String, dynamic>> exportData() {
    return _items.map((item) => itemToMap(item)).toList();
  }
  
  // 导入数据
  void importData(List<Map<String, dynamic>> data) {
    _items.value = data.map((item) => itemFromMap(item)).toList();
    _totalItems.value = _items.length;
  }
  
  // 子类需要实现的方法
  Future<ApiResult<PaginationResponse<T>>> fetchData({
    required int page,
    required int pageSize,
    String? keyword,
    Map<String, dynamic>? filters,
    String? sortBy,
    String? sortOrder,
  });
  
  // 子类可以重写的方法
  Map<String, dynamic> itemToMap(T item) {
    return {};
  }
  
  T itemFromMap(Map<String, dynamic> map) {
    throw UnimplementedError('itemFromMap must be implemented');
  }
}